<?php


namespace app\admin\model;


use app\admin\struct\PersonStruct;
use app\admin\validate\Person;
use app\crm\controller\Sign;
use app\crm\model\ShopPersonAchievementModel;
use app\crm\model\SignCert;
use think\facade\Db;
use think\helper\Arr;
use think\model\concern\SoftDelete;
use Yyz\test\src\YiYunzhang\RunTest as YzhRun;

class PersonModel extends Common
{
    use PersonStruct;

    use SoftDelete;

    // 设置字段信息
    protected $schema = [

    ];
    /**
     * 类型转换
     * @var string[]
     */
    protected $type = [

    ];
    /**
     * @var string
     */
    protected $name = 'shop_person';

    protected $deleteTime = 'delete_time';

    protected $defaultSoftDelete = 0;

    protected $autoWriteTimestamp = true;
    /**
     * 驼峰格式转换
     * @var bool
     */
    protected $convertNameToCamel = true;

    protected $append = [];

    /**
     * @return float
     * @author ran
     * @date 2021-11-18 15:49
     * mailbox 466180170@qq.com
     */
    public function getAchieveAmtAttr()
    {
         return $this->shopRefundOrder()->where('type', 3)->where('status','<>',3)->sum('pay_amount');
    }

    /**
     * @return float
     * @author ran
     * @date 2021-11-18 15:49
     * mailbox 466180170@qq.com
     */
    public function getNursNumberAttr()
    {
        return $this->shopRefundOrder()->where('type', 3)->where('status','<>',3)->count();
    }

    /**
     * @return \think\model\relation\HasMany
     * @author ran
     * @date 2021-11-18 15:04
     * mailbox 466180170@qq.com
     */
    public function shopOrder()
    {
        return $this->hasMany(ShopOrderModel::class, 'sale_id', 'id')->field('sale_id,sales_name');
    }
    /**
     * @return \think\model\relation\HasMany
     * @author ran
     * @date 2021-11-18 15:04
     * mailbox 466180170@qq.com
     */
    public function shopRefundOrder()
    {
        return $this->hasMany(ShopRefundOrderModel::class, 'sale_id', 'id')->field('sale_id,sales_name');
    }

    /**
     * 计算工龄
     * @return int
     * @author ran
     * @date 2021-11-18 15:04
     * mailbox 466180170@qq.com
     */
    public function getjobAgeAttr()
    {
        $entryAt = $this->getAttr('entryAt');
        return floor(((time() - strtotime($entryAt)) / (3600 * 24)) / 365);
    }

    /**
     * @return array
     * @author ran
     * @date 2021-10-16 16:54
     * mailbox 466180170@qq.com
     */
    private function getPersonCondition(array $request)
    {
        $where = [];
        $shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;
        $name = isset($request['name']) && trim($request['name']) ? trim($request['name']) : '';
        $shopId && array_push($where, ['shop_id', '=', $shopId]);
        $phone = isset($request['phone']) && trim($request['phone']) ? trim($request['phone']) : '';
        $positionId = isset($request['positionId']) && intval($request['positionId']) ? intval($request['positionId']) : 0;
        $positionIds = isset($request['positionIds']) && intval($request['positionIds']) ? intval($request['positionIds']) : 0;
        $status = isset($request['status']) && intval($request['status']) ? intval($request['status']) : 1;
        $name && array_push($where, ['name', 'like', '%' . $name . '%']);
        $phone && array_push($where, ['phone', '=', $phone]);
        //$positionId && array_push($where, ['position_id', '=', $positionId]);
        if(!empty($positionId) && $positionId == 2){
            //用于添加顾客时，获取所属咨询
            array_push($where, ['position_id', 'in', [1,2]]);
            array_push($where, ['id', '<>', 2]);
        }elseif(!empty($positionId)){
            array_push($where, ['position_id', '=', $positionId]);
        }

        $positionIds && array_push($where, ['position_id', 'in', $positionIds]);
        $status && array_push($where, ['status', '=', $status]);
        return $where;
    }

    /**
     * 创建员工资源
     * @param array $request
     * @return false
     * @author ran
     * @date 2021-09-16 15:43
     * mailbox 466180170@qq.com
     */
    public function createPersonResource(array $request)
    {
        $validate = new Person();
        if (!$validate->scene('create')->check($request)) {
            $this->error = $validate->getError();
            return false;
        }
        Db::startTrans();
        try {
            $re =$this->where('phone',$request['phone'])->find();
            if($re){
                throw new \Exception('员工账户手机号不能重复,请更换手机号');
            }
            $request['id_number'] = $request['idNumber']; //添加-身份证号
            $res = $this->create($request);
            if ($res->id) {
                if ($this->createShopPersonAdminUser($res->id, $request) === true) {
                    if(!empty($request['idNumber'])){
                        $data = [
                            'idCardNum'=>$request['idNumber'],
                            'newMobile'=>$request['phone'],
                            'real_name' => $request['name'],
                        ];
                        $cert = $this->createCerts($data);
                        if(isset($cert['code'])){
                            $certData = $cert['data'];
                            //入库证书
                            $certInsert =[
                                'person_id'=>$res->id,
                                'userNum'=>$certData['userNum'],
                                'serialNumber'=>$certData['serialNumber'],
                                'certNotBefore'=>$certData['certNotBefore'],
                                'certNotAfter'=>$certData['certNotAfter'],
                                'accId'=>$certData['accId'],
                                'userName'=>$certData['userName'],
                                'signId'=>$certData['signId'],
                                'issuer'=>$certData['issuer'],
                            ];
                            SignCert::create($certInsert);
                        }else{
                            throw new \Exception($cert['error']);
                        }
                    }

                    Db::commit();
                    return true;
                }
                throw new \Exception('店铺员工账户入库失败');
            }
            throw new \Exception('员工入库失败');

        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }


    //创建证书-签名使用
    public function createCerts($data){

        $this->signRun = new YzhRun();
        $url ='/ecs/account/applyCertString.jspa';
        $EsignArr=[
            'info'=>json_encode([
                'type'=>1,
                'cardType'=>'0',
                'idCardNum'=>$data['idCardNum'],
                'name'=>$data['real_name'],
                'mobilePhone'=>$data['newMobile']
            ]),'isSign'=>true,
        ];
        $signRes = $this->signRun->applyCertificateTest($EsignArr,$url,'post');

        if($signRes['meta']['code'] != 0 ){
            $returnArr =  ['error'=>$signRes['meta']['message']];
        }else{
            $returnArr =  ['code'=>200,'msg'=>'success','data'=>$signRes['data']];
        }
        return $returnArr;
    }

    /**
     * 更新员工信息
     * @param array $request
     * @return bool
     * @author ran
     * @date 2021-10-18 9:02
     * mailbox 466180170@qq.com
     */
    public function updatePersonAdminResource(array $request)
    {
        $validate = new Person();
        if (!$validate->scene('update')->check($request)) {
            $this->error = $validate->getError();
            return false;
        }
        try {
            $this->update($request);
            $this->updateShopPersonAdminUser($request);
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 创建店铺员工账户
     * @author ran
     * @date 2021-09-25 14:49
     * mailbox 466180170@qq.com
     */
    protected function createShopPersonAdminUser($id, array $request)
    {
        $adminUser = new User();
        $salt = substr(md5(time()), 0, 4);
        $data = [
            'shop_id' => $request['shopId'],
            'shop_person_id' => $id,
            'username' => $request['phone'],
            'realname' => $request['name'],
            'salt' => $salt,
            'password' => user_md5($request['password'], $salt, $request['phone']),
            'type' => 3,
            'sex' => $request['sex'],
            'group_id' => $request['groupId'],
            'mobile' => $request['phone'],
            'status' => $request['status'],
            'create_time' => time()

        ];
        try {
            $res = $adminUser->create($data);
            if ($res->id) {
                $accessModel = new Access();
                $data = [
                    'user_id' => $res->id,
                    'group_id' => $request['groupId'] ?? 0
                ];
                $accessModel->create($data);
            }
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }
    /**
     * 更新店铺员工账户
     * @author ran
     * @date 2021-09-25 14:49
     * mailbox 466180170@qq.com
     */
    protected function updateShopPersonAdminUser(array $request)
    {
        $adminUser = new User();
        $salt = substr(md5(time()), 0, 4);
        $data = [
            'username'=>$request['phone'],
            'shop_id' => $request['shopId'],
            'group_id'=>$request['groupId'],
        ];
        if (!empty($request['password'])) {
            $data['salt'] = $salt;
            $data['password'] = user_md5($request['password'], $salt, $request['phone']);
        }
        if($request['status']==3){
            $data['is_status']=1;
        }
        if($request['status']==1){
            $data['is_status']=0;
        }
        $userId =$adminUser->field('id')->where('shop_person_id',$request['id'])->value('id');
       // var_dump($data);
        try {
            $adminUser->update($data, ['shop_person_id' => $request['id']]);
            $accessModel = new Access();
            $access =$accessModel->where('user_id',$userId)->find();
            if($access){
                $accessModel->update(['group_id' => $request['groupId']],['user_id'=>$userId]);
            }else{
                $data = [
                    'user_id' => $userId,
                    'group_id' => $request['groupId'] ?? 0
                ];
                $accessModel->create($data);
            }

            $today = date('Ymd');
            //调整门店预约 -- begin
            $where = [
                ['shop_person_id','=',$request['id']],
                ['time','>=',$today]
            ];
            $shop_person_schedule_ids = DB::name('shop_person_schedule')->where($where)->column('id');
            if(!empty($shop_person_schedule_ids)){
                $update = [
                    'update_time'=>time(),
                    'remark'=>'护理师转店',
                    'shop_id'=>$request['shopId']
                ];
                DB::name('shop_person_schedule')->whereIn('id',$shop_person_schedule_ids)->update($update);
            }
            //调整门店预约 -- end
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 获取员工列表
     * @author ran
     * @date 2021-09-22 16:37
     * mailbox 466180170@qq.com
     */
    public function getPersonAdminListResource($shopIds, int $page, int $limit, $request)
    {


        $where = $this->getPersonCondition($request);


        $connect = $this->where($where)

            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            });
        $count =$connect->count();

        $list =$connect->page($page, $limit)->select();
        return [
            'list' => $list,
            'dataCount' => $count
        ];
    }
    /**
     * 销售出库单获取开单人员工
     * @author ran
     * @date 2021-09-22 16:37
     * mailbox 466180170@qq.com
     */
    public function getShopPersonListByRefundOrder($shopId, int $page, int $limit, $request)
    {
        $connect = $this->where(['shop_id'=>$shopId,'status'=>1]);
        $count =$connect->count();
        return [
            'list' => $connect->page($page, $limit)->select(),
            'dataCount' => $count
        ];
    }

    /**
     * 获取首页员工数据
     * @author ran
     * @date 2021-09-22 16:37
     * mailbox 466180170@qq.com
     */
    public function getPersonAdminListResourceServiceSys(array $shopIds, $request, int $page, int $limit)
    {
       $field = ['id', 'name'];
        if(empty($request['startTime'])){
            $startTime =strtotime(date('Y-m-01 00:00:00'));
        }else{
            $startTime =strtotime($request['startTime']);
        }
        if(empty($request['endTime'])){
            $endTime =strtotime(date('Y-m-d',strtotime(date('Y-m-1',strtotime('next month')).'-1 day')));
        }else{
            $endTime =strtotime($request['endTime']);
        }
        //一号护理师
        $oneNurse =Db::name('service_log')->field('count(id) as number,nurse_id_one')
            ->where([['create_time', 'between', "$startTime,$endTime"]])
            ->group('nurse_id_one')->select()->toArray();
        $oneNurse=array_column($oneNurse,null,'nurse_id_one');
        //二号护理师 护理量0.5
        $twoNurse =Db::name('service_log')->field('count(id) as c,nurse_id_two')
            ->where([['create_time', 'between', "$startTime,$endTime"]])
            ->group('nurse_id_two')->select()->toArray();
        $twoNurse=array_column($twoNurse,null,'nurse_id_two');
        //护理师业绩
        $achieveAmt =Db::name('shop_refund_order')
            ->field('sum(pay_amount) as money,sale_id')
            ->where('refund_type','<>','101.03')
            ->where('type', 3)
            ->where([['deal_time', 'between', "$startTime,$endTime"]])
            ->where('status','<>',3)
            ->group('sale_id')->select()->toArray();

        $achieveAmt=array_column($achieveAmt,null,'sale_id');
        $connect = $this->field($field)
            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            });
        $list =empty($connect) ? [] : $connect->page($page, $limit)->select()->toArray();
        foreach($list as $key=>$value){
            $oneNurseNumber =$oneNurse[$value['id']]['number']??0;
            $twoNurseNumber =$twoNurse[$value['id']]['number']??0;
            $nursNumber =$oneNurseNumber+$twoNurseNumber*0.5;
            $list[$key]['nursNumber']=$nursNumber;
            $list[$key]['achieveAmt']=$achieveAmt[$value['id']]['money']??0;
        }
        return $list;
    }

    /**
     * 获取 员工信息
     * @param int $id
     * @author ran
     * @date 2021-10-18 9:02
     * mailbox 466180170@qq.com
     */
    public function getPersonAdminInfoResource(int $id)
    {
        $person = $this->find($id);
        $person['idNumber'] = !empty($person['idNumber'])? substr_replace($person['idNumber'],str_repeat("*",6),6,6):"";
        return $person;
    }

    /**
     * 店铺资源导出
     * @author ran
     * @date 2021-12-01 11:56
     * mailbox 466180170@qq.com
     */
    public function exportAdminPersonListResoure(array $shopIds, array $request, array $ids)
    {
        $where = $this->getPersonCondition($request);
        $field = [
            'id', 'name', 'phone', 'entry_at', 'is_probation', 'sex', 'shop_name',
            'station_name', 'position_name', 'status', 'age', 'job_age'
        ];
        $list = $this->where($where)->field($field)
            ->when($ids ?? [], function ($query) use ($ids) {
                return $query->whereIn('id', $ids);
            })
            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            })->page(1, 10000)->select()->toArray();
        foreach ($list as &$v) {
            $v['statusDesc'] = $v['status'] == 1 ? '在职' : '离职';
            $v['isProbation'] = $v['isProbation'] == 1 ? '否' : '是';
        }
        $callName = [
            'id' => '员工id', 'name' => '员工名称', 'phone' => '员工电话',
            'sex' => '性别', 'isProbation' => '是否通过试用期', 'entryAt' => '入职时间',
            'shopName' => '归属门店', 'positionName' => '职务', 'stationName' => '岗位',
            'statusDesc' => '状态', 'jobAge' => '工龄',
        ];
        $downUrl = exportExcelData('person', $callName, $list, 'xlsx', 1);
        return [
            'url' => 'http://' . $_SERVER['HTTP_HOST'] . $downUrl,
        ];
    }

    /**
     * 员工业绩统计
     * @author ran
     * @date 2021-12-04 11:39
     * mailbox 466180170@qq.com
     */
    /*public function getAdminShopPersonStatistics($shopIds,$request,int $page, int $limit)
    {

        $startTimeToday =strtotime($request['end_time']);
        $endTimeToday =strtotime($request['end_time'])+60*60*24-1;
        $monthdate =date('Y-m',strtotime($request['end_time']));
        $field = ['id','name','grade_name as gradeName'];
        $list = Db::name('shop_person')->field($field)
            ->where('status','<>',3)->page(1, 200)
            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            })->select()
            ->toArray();
        // print_r($list);eixt;
        $pids =array_column($list,'id');
        $category =$this->getPushCategoryArray();
        $ids =array_column($category,'id');

        // 获取当天服务量
        // 比例为1的
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_one','in',$pids]);
        array_push($where,['nurse_id_two','=',0]);
        array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
        $arr1 =Db::name('service_log')
            ->field('nurse_id_one as personId,category_id')
            ->where($where)
            ->select()->toArray();
        // print_r($arr);exit;
        // 比例为0.5的
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_one','in',$pids]);
        array_push($where,['nurse_id_two','>',0]);
        array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
        $arr2 =Db::name('service_log')
            ->field('nurse_id_one as personId,category_id')
            ->where($where)
            ->select()->toArray();
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_two','in',$pids]);
        array_push($where,['nurse_id_one','>',0]);
        array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
        $arr3 =Db::name('service_log')
            ->field('nurse_id_two as personId,category_id')
            ->where($where)
            ->select()->toArray();
        $result = array();
        foreach($arr1 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($result[$key])){
                $val['number'] = 1;
                $result[$key] = $val;
            }else{
                $result[$key]['number'] += 1;
            }
        }
        foreach($arr2 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($result[$key])){
                $val['number'] = 0.5;
                $result[$key] = $val;
            }else{
                $result[$key]['number'] += 0.5;
            }
        }
        foreach($arr3 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($result[$key])){
                $val['number'] = 0.5;
                $result[$key] = $val;
            }else{
                $result[$key]['number'] += 0.5;
            }
        }


        // 获取当月的服务量
        // 比例为1的
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_one','in',$pids]);
        array_push($where,['nurse_id_two','=',0]);
        $arr1 =Db::name('service_log')
            ->field('nurse_id_one as personId,category_id')
            ->where($where)
            ->whereMonth('create_time', $monthdate)
            ->select()->toArray();
        // print_r($arr);exit;
        // 比例为0.5的
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_one','in',$pids]);
        array_push($where,['nurse_id_two','>',0]);
        $arr2 =Db::name('service_log')
            ->field('nurse_id_one as personId,category_id')
            ->where($where)
            ->whereMonth('create_time', $monthdate)
            ->select()->toArray();
        $where = [];
        array_push($where,['category_id','in',$ids]);
        array_push($where,['nurse_id_two','in',$pids]);
        array_push($where,['nurse_id_one','>',0]);
        $arr3 =Db::name('service_log')
            ->field('nurse_id_two as personId,category_id')
            ->where($where)
            ->whereMonth('create_time', $monthdate)
            ->select()->toArray();
        $resultM = array();
        foreach($arr1 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($resultM[$key])){
                $val['number'] = 1;
                $resultM[$key] = $val;
            }else{
                $resultM[$key]['number'] += 1;
            }
        }
        foreach($arr2 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($resultM[$key])){
                $val['number'] = 0.5;
                $resultM[$key] = $val;
            }else{
                $resultM[$key]['number'] += 0.5;
            }
        }
        foreach($arr3 as $val){
            $key = $val['personId'].'_'.$val['category_id'];
            if(!isset($resultM[$key])){
                $val['number'] = 0.5;
                $resultM[$key] = $val;
            }else{
                $resultM[$key]['number'] += 0.5;
            }
        }
        //计算当天服务量
        // $arr =Db::name('service_log')
        //     ->field('nurse_id_one as personId,category_id')
        //     ->where(function($query) use ($pids){
        //         $query->where('nurse_id_one','in',$pids)
        //             ->whereOr('nurse_id_two','in',$pids);
        //     })
        //     ->where([['create_time', 'between', "$startTimeToday,$endTimeToday"]])
        //     ->whereIn('category_id',$ids)
        //     ->select()->toArray();
        // print_r($arr);eixt;
        //计算本月的服务量
        // $month =Db::name('service_log')
        //     ->field('nurse_id_one as personId,category_id')
        //     ->where(function($query) use ($pids){
        //         $query->where('nurse_id_one','in',$pids)
        //             ->whereOr('nurse_id_two','in',$pids);
        //     })
        //     ->whereMonth('create_time', $monthdate)
        //     ->whereIn('category_id',$ids)
        //     ->select()->toArray();
        // //当月
        // foreach($month as $key=>$value){
        //     $month[$key]['number']=1;
        // }
        // $resultM = array();
        // foreach($month as $val){
        //     $key = $val['personId'].'_'.$val['category_id'];
        //     if(!isset( $resultM[$key])){
        //         $resultM[$key] = $val;
        //     }else{
        //         $resultM[$key]['number'] += $val['number'];
        //     }
        // }
        //当日
        // foreach($arr as $key=>$value){
        //     $arr[$key]['number']=1;
        // }
        // $result = array();
        // foreach($arr as $val){
        //     $key = $val['personId'].'_'.$val['category_id'];
        //     if(!isset($result[$key])){
        //         $result[$key] = $val;
        //     }else{
        //         $result[$key]['number'] += $val['number'];
        //     }
        // }

        // print_r($result);eixt;
        //计算医师直接成交当日
        $yishi =Db::name('shop_refund_order')
            ->field('sum(pay_amount) as money,sale_id')
            ->where('status','<>',3)
            ->where('type',3)
            ->where([['deal_time', 'between', "$startTimeToday,$endTimeToday"]])
            ->where('order_type',1)->group('sale_id')->select()->toArray();
        //计算医师直接成交当月
        $yishimoth =Db::name('shop_refund_order')
            ->field('sum(pay_amount) as money,sale_id')
            ->where('status','<>',3)
            ->where('type',3)
            ->whereMonth('deal_time', $monthdate)
            ->where('order_type',1)->group('sale_id')->select()->toArray();
        $yishi=array_column($yishi,null,'sale_id');
        $yishimoth=array_column($yishimoth,null,'sale_id');
        $category =$this->getPushCategoryArray();
        foreach ($list as $key=>$value){
            foreach($category as $k=>$v){
                $id =$v['id']??0;
                $keys =$value['id'].'_'.$id;
                if($id ==14){
                    $number=$yishi[$value['id']]['money']??0;
                    $Mnumber=$yishimoth[$value['id']]['money']??0;
                }else{
                    $number=$result[$keys]['number']??0;
                    $Mnumber=$resultM[$keys]['number']??0;
                }
                $category[$k]['number'] =$number;
                $category[$k]['Mnumber'] =$Mnumber;
                //$category[$k]['thirdOneDay'] =round(bcmul($number,$v['percentage']),2);
				$category[$k]['thirdOneDay'] =$number;
                //$category[$k]['monthPayTotalPrice'] =round(bcmul($Mnumber,$v['percentage']),2);

                $category[$k]['monthPayTotalPrice'] =$Mnumber;

                $category[$k]['percentageStandard'] =$v['percentage'];
                $category[$k]['personAchieve'] =round(bcmul($number,$v['percentage']),2);
                $category[$k]['monthPercentage'] =round(bcmul($Mnumber,$v['percentage']),2);
            }
            $list[$key]['goods'] =$category;
        }
        return [
            'list' => $list,
            'dataCount' =>0
        ];
    }*/
    public function getAdminShopPersonStatistics($shopIds,$request){
        $start_time =strtotime($request['start_time']);
        $end = date('Y-m-t',$start_time);
        $end_time =strtotime($end);
        $where = [];
        array_push($where,['a.time','between',[$start_time,$end_time+24*60*60-1]]);
        if(!empty($shopIds))
        {
            array_push($where,['b.shop_id','in',$shopIds]);
        }
        $list = Db::name('shop_person_achievement')
            ->field('b.name,b.grade_name as gradeName,a.*,a.sum*a.commission as commissionMoney')
            ->alias('a')
            ->join('shop_person b','b.id = a.person_id','left')
            ->where($where)->order('a.person_id asc,a.id')->select()->toArray();
        $count = count($list);
        $name = [
            'serviceNum'=>"护理量",
            'outreachNum'=>"外联进店",
            'newOrderReal'=>"新单成交金额",
            'repairOrderReal'=>"补单成交金额",
            'outreachReal'=>"外联进店成交",
            'introductionReal'=>"转介绍成交",
            'experienceReal'=>"护理师体验成交",

        ];
        foreach ($list as $key => $value)
        {
            $list[$key]['goodsName']=$name[$value['type']]??"";
        }
        /*$list = Db::name('shop_person')
            ->where('status','<>',3)
            ->when($shopIds ?? [], function ($query) use ($shopIds) {
                return $query->whereIn('shop_id', $shopIds);
            })->column('id,name,grade_name as gradeName','id');
        $personIds = array_column($list,'id');
        $count = count($list);
        $where = [];
        array_push($where,['person_id','in',$personIds]);
        array_push($where,['time','between',[$start_time,$end_time+24*60*60-1]]);
        $name = [
            'serviceNum'=>"护理量",
            'outreachNum'=>"外联进店",
            'newOrderReal'=>"新单成交金额",
            'repairOrderReal'=>"补单成交金额",
            'outreachReal'=>"外联进店成交",
            'introductionReal'=>"转介绍成交",
            'experienceReal'=>"护理师体验成交",

        ];
        $data = ShopPersonAchievementModel::where($where)->order('time asc')->select()->toArray();
        foreach ($list as $key =>$value)
        {
            $list[$key]['goods']['serviceNum']=['goodsName'=>$name['serviceNum']];
            $list[$key]['goods']['outreachNum']=['goodsName'=>$name['outreachNum']];
            $list[$key]['goods']['newOrderReal']=['goodsName'=>$name['newOrderReal']];
            $list[$key]['goods']['repairOrderReal']=['goodsName'=>$name['repairOrderReal']];
            $list[$key]['goods']['outreachReal']=['goodsName'=>$name['outreachReal']];
            $list[$key]['goods']['introductionReal']=['goodsName'=>$name['introductionReal']];
            $list[$key]['goods']['experienceReal']=['goodsName'=>$name['experienceReal']];
        }
        $result = [];
        foreach ($data as $key => $value)
        {
            $result[$key] = $list[$value['person_id']];
            if($value['is_sum'] == 0)
            {
                array_push($list[$value['person_id']]['goods']['serviceNum'],$value['serviceNum']);
                array_push($list[$value['person_id']]['goods']['outreachNum'],$value['outreachNum']);
                array_push($list[$value['person_id']]['goods']['newOrderReal'],$value['newOrderReal']);
                array_push($list[$value['person_id']]['goods']['repairOrderReal'],$value['repairOrderReal']);
                array_push($list[$value['person_id']]['goods']['outreachReal'],$value['outreachReal']);
                array_push($list[$value['person_id']]['goods']['introductionReal'],$value['introductionReal']);
                array_push($list[$value['person_id']]['goods']['experienceReal'],$value['experienceReal']);
            }else{
                $list[$value['person_id']]['goods']['serviceNum']['sum']=$value['serviceNum'];
                $list[$value['person_id']]['goods']['outreachNum']['sum']=$value['outreachNum'];
                $list[$value['person_id']]['goods']['newOrderReal']['sum']=$value['newOrderReal'];
                $list[$value['person_id']]['goods']['repairOrderReal']['sum']=$value['repairOrderReal'];
                $list[$value['person_id']]['goods']['outreachReal']['sum']=$value['outreachReal'];
                $list[$value['person_id']]['goods']['introductionReal']['sum']=$value['introductionReal'];
                $list[$value['person_id']]['goods']['experienceReal']['sum']=$value['experienceReal'];
            }
        }
        foreach ($list as $key =>$value)
        {
            $list[$key]['goods'] = array_values($value['goods']);
        }*/
        return [
            'list'=>array_merge($list,[]),
            'dataCount'=>$count
        ];

    }
    public function getDayAdminShopPersonStatistics(&$list,$start_time,$end_time)
    {
        $idS = array_column($list,'id');
        $where = [];
        array_push($where,['create_time','>=',$start_time]);
        array_push($where,['create_time','<=',$end_time]);

        $serviceOneNum = Db::name('service_log')->where($where)->where('nurse_id_one','in',$idS)->group('nurse_id_one')->column('count(*)','nurse_id_one');
        $serviceTwoNum = Db::name('service_log')->where($where)->where('nurse_id_two','in',$idS)->group('nurse_id_two')->column('count(*)','nurse_id_two');

        $outreachNum = Db::name('customer')->where('operator','in',$idS)->where(function ($query)use($start_time,$end_time){
            $query->whereOr([
                ['first_time','between',[$start_time,$end_time]],
                ['second_time','between',[$start_time,$end_time]]
            ]);
        })->group('operator')->column('count(*)','operator');

        $where = [];
        array_push($where,['order_type','=',1]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $newOrderReal = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');
        $where = [];
        array_push($where,['order_type','=',1]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $newOrderRefund = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(total_amount)','operator_id');

        $where = [];
        array_push($where,['order_type','=',2]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $repairOrderReal = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');
        $where = [];
        array_push($where,['order_type','=',2]);
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $repairOrderRefund = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(total_amount)','operator_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_outreach','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $outreachReal = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_outreach','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $outreachRefund = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_introduction','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $introductionReal = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_introduction','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $introductionRefund = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');

        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',3]);
        array_push($where,['is_experience','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $experienceReal = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');
        $where = [];
        array_push($where,['status','=',2]);
        array_push($where,['type','=',1]);
        array_push($where,['is_experience','=',1]);
        array_push($where,['deal_time','between',[$start_time,$end_time]]);
        array_push($where,['operator_id','in',$idS]);
        $experienceRefund = Db::name('shop_refund_order')->where($where)->group('operator_id')->column('sum(pay_amount)','operator_id');


        foreach ($list as $key =>$value)
        {
            $temp['serviceNum']=$serviceOneNum[$key]??0;
            if(!empty($serviceTwoNum[$key]))
            {
                $temp['serviceNum']+=$serviceTwoNum[$key];
            }
            $temp['outreachNum']=$outreachNum[$key]??0;
            $temp['newOrderReal']=$newOrderReal[$key]??0;
            if(!empty($newOrderRefund[$key]))
            {
                $temp['newOrderReal']-=$newOrderRefund[$key];
            }
            $temp['repairOrderReal']=$repairOrderReal[$key]??0;
            if(!empty($repairOrderRefund[$key]))
            {
                $temp['repairOrderReal']-=$repairOrderRefund[$key];
            }
            $temp['outreachReal']=$outreachReal[$key]??0;
            if(!empty($outreachRefund[$key]))
            {
                $temp['outreachReal']-=$outreachRefund[$key];
            }
            $temp['introductionReal']=$introductionReal[$key]??0;
            if(!empty($introductionRefund[$key]))
            {
                $temp['introductionReal']-=$introductionRefund[$key];
            }
            $temp['experienceReal']=$experienceReal[$key]??0;
            if(!empty($experienceRefund[$key]))
            {
                $temp['experienceReal']-=$experienceRefund[$key];
            }
            array_push($list[$key]['serviceNum'],$temp['serviceNum']);
            array_push($list[$key]['outreachNum'],$temp['outreachNum']);
            array_push($list[$key]['newOrderReal'],$temp['newOrderReal']);
            array_push($list[$key]['repairOrderReal'],$temp['repairOrderReal']);
            array_push($list[$key]['outreachReal'],$temp['outreachReal']);
            array_push($list[$key]['introductionReal'],$temp['introductionReal']);
            array_push($list[$key]['experienceReal'],$temp['experienceReal']);

        }
        return $list;
    }
    public function getPushCategoryArray(){
        return [
            [
                'id'=>1,
                'goodsName'=>'疤痘护理',
                'percentage'=>6,
            ],
            [
                'id'=>8,
                'goodsName'=>'面部护理',
                'percentage'=>6,
            ],
            [
                'id'=>10,
                'goodsName'=>'项目身体护理',
                'percentage'=>6,
            ],
            [
                'id'=>11,
                'goodsName'=>'生命之源/经络通/疏肝理气',
                'percentage'=>6,
            ],
            [
                'id'=>12,
                'goodsName'=>'基础补水',
                'percentage'=>3,
            ],
            [
                'id'=>13,
                'goodsName'=>'外联/个人自媒体进店',
                'percentage'=>10,
            ],
            [
                'id'=>14,
                'goodsName'=>'医师直接成交',
                'percentage'=>0.025,
            ],
            [
                'goodsName'=>'医师体验成交',
                'percentage'=>0.025,
            ],
            [
                'goodsName'=>'疤痘销售',
                'percentage'=>0.03,
            ],
            [
                'goodsName'=>'项目/美肌销售',
                'percentage'=>0.03,
            ],
            [
                'goodsName'=>'护肤品销售（非疤痘攻效）',
                'percentage'=>0.04,
            ],
            [
                'goodsName'=>'医疗转诊',
                'percentage'=>0.08,
            ],
            [
                'goodsName'=>'外联/自媒体进店成交',
                'percentage'=>0.02,
            ],
            [
                'goodsName'=>'转介绍成交',
                'percentage'=>0.10,
            ],
            [
                'goodsName'=>'护理师体验成交',
                'percentage'=>0.025,
            ]
        ];
    }
    /**
     * 员工业绩统计
     * @author ran
     * @date 2021-12-04 11:39
     * mailbox 466180170@qq.com
     */
    public function getAdminShopPersonStatisticsBak(int $page, int $limit)
    {
        $list=$this->structShopPersonOrderGroupBySaleId($page,$limit);
        $saleIds =Arr::pluck($list['list'],'saleId');
        $goods =$this->getShopPersonOrderBySaleIds($list['list'],$saleIds);
        return [
            'list' => $goods,
            'dataCount' => $list['count']
        ];
    }
    /**
     * 构造数据
     * @param $page
     * @param $limit
     * @return array
     * @author ran
     * @date 2021-12-04 15:53
     * mailbox 466180170@qq.com
     */
    public function structShopPersonOrderGroupBySaleId($page,$limit):array
    {
        $data=[];
        $shopOrderModel = new ShopOrderModel();
        $list = $shopOrderModel->getShopOrderGroupBySaleId($page,$limit);
        foreach ($list['list'] as $val) {
            $data[] = [
                'saleId' => $val['saleId']??'',
                'name' => $val['person']['name']??'',
                'positionName' => $val['person']['positionName']??'',
            ];
        }
        return ['count' => $list['count'], 'list' =>$data];
    }
    /**
     * @author ran
     * @date 2021-12-04 13:23
     * mailbox 466180170@qq.com
     */
    public function getShopPersonOrderBySaleIds($request,$list,$saleIds)
    {
        $goods = [];
        $shopOrderModel = new ShopOrderModel();
        $field = ['id', 'order_no', 'sale_id'];
        $arr = $shopOrderModel->getShopPersonOrder($request,$field, $saleIds);
        foreach ($arr as $value) {
            foreach ($value['shopOrderGoods'] as $val) {
                $goods[] = [
                    'id' => $val['id'],
                    'saleId' => $value['saleId'],
                    'goodsId' => $val['goodsId'],
                    'goodsName' => $val['goodsName'],
                    'thirdOneDay' => $val['payPrice']*$val['number'],
                    'monthPayTotalPrice' => $val['payPrice']*$val['number'],
                    'percentageStandard' => 3,
                    'personAchieve' => 0,
                    'monthPercentage' => 3,
                ];
            }
        }
        $goods =array_group_by(goRepeatArraySum($goods,'monthPayTotalPrice','goodsId','saleId'),'saleId');
        foreach($list as $key=>$value){
            $list[$key]['goods']=$goods[$value['saleId']]??[];
        }
        return $list;
    }

    /**
     * @param $saleId
     * @param $goodsId
     * @param $month
     * @author ran
     * @date 2021-12-18 20:48
     * mailbox 466180170@qq.com
     */
    public function sumThirdOneDayMoney($saleId,$goodsId,$month){
        $shopOrderGoodsModel = new ShopOrderGoodsModel();
        /* $count =$shopOrderGoodsModel
            ->alias('g')
            ->leftjoin('shop_order o','g.order_id = o.id')
            ->where('o.sale_id',$saleId)
            ->where('g.goods_id',$goodsId)
            ->when($month ?? [], function ($query) use ($month) {
                return $query->whereMonth('g.create_time', $month);
            })->sum('g.number');*/
        return $shopOrderGoodsModel
            ->alias('g')
            ->leftjoin('shop_order o','g.order_id = o.id')
            ->where('o.sale_id',$saleId)
            ->where('g.goods_id',$goodsId)
            ->when($month ?? [], function ($query) use ($month) {
                return $query->whereMonth('g.create_time', $month);
            })->sum('g.pay_price');
    }
    /**
     * @param $request
     * @return bool
     * @author ran
     * @date 2022-02-25 13:10
     * mailbox 466180170@qq.com
     */
    public function createShopTask($request){
        $month =$request['month']??0;
        $time =strtotime($month);
        $data =[
            'shop_id'=>$request['shopId']??0,
            'month'=>$time,
            'price'=>$request['price']??0,
            'market_id'=>$request['marketId']??0,
            'create_time'=>time()
        ];
        $where=['shop_id'=>$request['shopId']??0,'month'=>$request['month']??0];
        $res = Db::name('shop_task')->where($where)->find();
        if($res){
            $this->error = '该门店当月已经创建任务';
            return false;
        }
        Db::name('shop_task')->insert($data);
        return true;
    }

    /**
     * 批量导入门店任务
     *
     * @param $request
     * @return bool
     */
    public function importShopAchievementExcel($request)
    {
        $time= strtotime($request['date']);
        $path = $request['file']->getPathname();
        $data = readExcelData($path);
        $insertData = [];
        $now = time();
        foreach ($data as $value)
        {
            if(empty($value[3]))
                continue;
            $temp = [
                'shop_id'=>$value[1]??0,
                'month'=>$time,
                'price'=>$value[3]??0,
                'price_base'=>$value[4]??0,
                'market_id'=>$value[0]??0,
                'create_time'=>$now
            ];
            $where = [];
            array_push($where,['shop_id','=',$value[1]]);
            array_push($where,['month','=',$time]);
            $result = Db::name('shop_task')->where($where)->find();
            if($result){
                $temp['id']=$result['id'];
            }

            array_push($insertData,$temp);
        }
        $shopTask = new ShopTask();
//        print_r($insertData);
//        exit;
        $res = $shopTask->saveAll($insertData);
        if(!$res)
        {
            $this->error = '创建任务失败';
            return false;
        }
        return true;
    }
    /**
     * 正在营业店铺列表
     */
    public function getAgentShopList()
    {
        $where = [];
        array_push($where,['status','=',1]);
        $shopInfo  = Db::name('shop')
        ->field('shop_id,shop_name')
        ->where($where)
        ->select()->toArray();
        return $shopInfo;
    }
    /**
     * 代理店长列表
     */
    public function getAgentList()
    {
        $where = [];
        array_push($where,['group_id','=',118]);
        $data = Db::name('admin_user')
            ->field('id,realname,mobile')
            ->where($where)
            ->select()->toArray();
        foreach($data as $key => $value)
        {
            $where = [];
            array_push($where,['a.user_id','=',$value['id']]);
            array_push($where,['a.status','=',1]);
            $shopInfo  = Db::name('admin_user_agent')->alias('a')
                ->field('a.shop_id,b.shop_name')
                ->join('shop b','a.shop_id = b.shop_id')
                ->where($where)
                ->select()->toArray();
            $data[$key]['shopInfo'] = $shopInfo;
            $data[$key]['shopId'] = array_column($shopInfo,'shop_id');
            // $data[$key]['shopId'] = implode(',',$data[$key]['shopId']);
            // $data[$key]['shopId'] = '['.$data[$key]['shopId'].']';
            $shopName = array_column($shopInfo,'shop_name');
            $shopName = implode(" ",$shopName);
            $data[$key]['shopName'] = $shopName;
        }
        return $data;
    }
    /**
     * 修改代理店长下属门店
     */
    public function setShopAgent($request)
    {
        $id = $request['id'];
        $shopIds = $request['shop_ids'];
        try{
            $where = [];
            array_push($where,['user_id','=',$id]);
            $res = Db::name('admin_user_agent')->where($where)->update(['status'=>0]);
            foreach($shopIds as $value)
            {
                $where = [];
                array_push($where,['user_id','=',$id]);
                array_push($where,['shop_id','=',$value]);
                $res = Db::name('admin_user_agent')->where($where)->find();
                if($res)
                {
                    $res = Db::name('admin_user_agent')->where($where)->update(['status'=>1]);
                }else{
                    $res = Db::name('admin_user_agent')->insert([
                        'user_id'=>$id,
                        'shop_id'=>$value,
                        'status'=>1
                    ]);
                }
            }
            return true;

        } catch (\Exception $e) {
            $this->error = '添加服务记录失败';
            return [];
        }
    }


}
